<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="60%"
             :append-to-body="true" @open="beforeOpen">
    <xum-title title="选择图片" :title-span="20">
      <el-input v-model="tempName" size="mini" @keypress.enter.native="changeTempName">
        <el-button type="text" size="mini" icon="el-icon-search" @click="changeTempName" slot="suffix"/>
      </el-input>
    </xum-title>
    <file-collection ref="selector" :name="trueName" :multiple="multiple"/>
    <div slot="footer">
      <el-button type="primary" @click="handleOk" size="small">确定</el-button>
      <el-button @click="reset" size="small">重置</el-button>
      <el-button @click="closeDialog" size="small">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import FileCollection from '@/components/upload/FileCollection'
import XumTitle from '@/components/XumTitle'
export default {
  name: 'FileCollectionSelectDialog',
  components: { XumTitle, FileCollection },
  props: {
    visible: {
      required: false,
      type: Boolean,
      default: false
    },
    name: {
      required: false,
      type: String,
      default: ''
    },
    multiple: {
      required: false,
      type: Boolean,
      default: true
    },
    title: {
      required: false,
      type: String,
      default: '选择图片'
    }
  },
  model: {
    event: 'change',
    prop: 'visible'
  },
  data () {
    return {
      dialogVisible: false,
      tempName: '',
      trueName: ''
    }
  },
  mounted () {
    this.trueName = this.name
    this.tempName = this.name
  },
  methods: {
    /**
     * 初始化数据
     */
    initData () {
    },
    /**
     * 对话框打开前初始化数据
     */
    beforeOpen () {
      this.initData()
    },
    /**
     * 对话框关闭按钮关闭对话框
     */
    closeDialog () {
      this.dialogVisible = false
    },
    /**
     * 重置按钮重置对话框数据
     */
    reset () {
      this.$refs['selector'].reset()
    },
    /**
     * 获取选择的文件
     * @return {Array<Object>} 选择的文件
     */
    getSelectFiles () {
      return this.$refs['selector'].getSelectFiles()
    },
    /**
     * 确定选择文件
     */
    handleOk () {
      const files = this.getSelectFiles()
      if (!files || typeof files !== 'object' || files.length <= 0) {
        this.$message.info('请先选择图片')
        return
      }
      this.$emit('fileChange', files)
      this.dialogVisible = false
    },
    /**
     * 用户输入后改变tempName
     */
    changeTempName () {
      if (this.tempName !== this.trueName) {
        this.trueName = this.tempName
      }
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val
    },
    dialogVisible (val) {
      this.$emit('change', val)
    },
    name (val) {
      this.trueName = val
      this.tempName = val
    }
  }
}
</script>

<style scoped>

</style>
